
import sys, os, struct, re

def convert_dsim(base):

    file_path = 'data/%s.data' % base
    file_size = os.path.getsize(file_path)
    if (file_size == 0):
        return 0

    fn0 = 'dsim/%s_00.hex' % base
    fn1 = 'dsim/%s_01.hex' % base
    fn2 = 'dsim/%s_02.hex' % base
    fn3 = 'dsim/%s_03.hex' % base

    f0 = open(fn0, 'w+')
    f1 = open(fn1, 'w+')
    f2 = open(fn2, 'w+')
    f3 = open(fn3, 'w+')

    lno = 0
    fb = open('data/%s.data' % base, 'rb')
    while True:
        d = fb.read(4)
        if len(d) != 4:
            break
        lno += 1
        d0, d1, d2, d3 = struct.unpack("BBBB", d)
        f0.write(f'{d0:02x}\n')
        f1.write(f'{d1:02x}\n')
        f2.write(f'{d2:02x}\n')
        f3.write(f'{d3:02x}\n')

    f0.close()
    f1.close()
    f2.close()
    f3.close()
    return lno


def convert_data(base):

    file_path = 'data/%s.data' % base
    file_size = os.path.getsize(file_path)
    if (file_size == 0):
        return 0

    fn0 = 'dhex/%s_00.dat' % base
    fn1 = 'dhex/%s_01.dat' % base
    fn2 = 'dhex/%s_02.dat' % base
    fn3 = 'dhex/%s_03.dat' % base

    f0 = open(fn0, 'w+')
    f1 = open(fn1, 'w+')
    f2 = open(fn2, 'w+')
    f3 = open(fn3, 'w+')

    f0.write("@0000\n")
    f1.write("@0000\n")
    f2.write("@0000\n")
    f3.write("@0000\n")

    lno = 0
    fb = open('data/%s.data' % base, 'rb')
    while True:
        d = fb.read(4)
        if len(d) != 4:
            break
        lno += 1
        d0, d1, d2, d3 = struct.unpack("BBBB", d)
        f0.write(f'{d0:08b}\n')
        f1.write(f'{d1:08b}\n')
        f2.write(f'{d2:08b}\n')
        f3.write(f'{d3:08b}\n')

    d0, d1, d2, d3 = 0, 0, 0, 0
    for i in range(lno, 4096):
        f0.write(f'{d0:08b}\n')
        f1.write(f'{d1:08b}\n')
        f2.write(f'{d2:08b}\n')
        f3.write(f'{d3:08b}\n')

    f0.close()
    f1.close()
    f2.close()
    f3.close()
    return lno

def main():
    fn = sys.argv[1]
    base = fn[5:-5]
    n = convert_dsim(base)
    n = convert_data(base)
    f = open('cnt/%s.dcnt' % base, 'w+')
    f.write("n = %d\n" % n)
    f.close()

if __name__=="__main__":
    main()

